<template>
  <div class="exam-take-container">
    <div class="exam-header">
      <div class="exam-info">
        <h2 class="exam-title">{{ exam.title }}</h2>
        <div class="exam-meta">
          <span class="course-name">{{ exam.courseName }}</span>
          <span class="exam-type">{{ getExamTypeText(exam.type) }}</span>
        </div>
      </div>
      <div class="exam-timer">
        <div class="timer-label">剩余时间</div>
        <count-down 
          :time="remainingTime" 
          :auto-start="true"
          @end="handleTimeUp"
          class="timer"
        ></count-down>
      </div>
    </div>
    
    <div class="exam-body">
      <div class="question-nav">
        <div class="nav-header">
          <div class="question-count">
            <span>题目</span>
            <span class="count">{{ currentQuestionIndex + 1 }}/{{ questions.length }}</span>
          </div>
          <div class="question-progress">
            <el-progress 
              :percentage="progressPercentage" 
              :stroke-width="8"
              :format="() => `${answeredCount}/${questions.length}`"
              :color="progressColor"
            ></el-progress>
          </div>
        </div>
        
        <div class="question-buttons">
          <el-button 
            v-for="(q, index) in questions" 
            :key="index"
            :type="getQuestionButtonType(index)"
            :plain="currentQuestionIndex !== index"
            size="small"
            class="question-button"
            @click="goToQuestion(index)"
          >
            {{ index + 1 }}
          </el-button>
        </div>
        
        <div class="question-legend">
          <div class="legend-item">
            <div class="legend-color" style="background-color: #409EFF;"></div>
            <div class="legend-text">当前题目</div>
          </div>
          <div class="legend-item">
            <div class="legend-color" style="background-color: #67C23A;"></div>
            <div class="legend-text">已回答</div>
          </div>
          <div class="legend-item">
            <div class="legend-color" style="background-color: #F56C6C;"></div>
            <div class="legend-text">标记题目</div>
          </div>
        </div>
      </div>
      
      <div class="question-content">
        <div class="question-header">
          <div class="question-type-tag">{{ getQuestionTypeText(currentQuestion.type) }}</div>
          <div class="question-score">{{ currentQuestion.score }}分</div>
        </div>
        
        <div class="question-title">
          <span class="question-index">{{ currentQuestionIndex + 1 }}. </span>
          <span v-html="currentQuestion.content"></span>
        </div>
        
        <!-- 单选题 -->
        <div v-if="currentQuestion.type === 'single'" class="question-options">
          <el-radio-group v-model="userAnswers[currentQuestionIndex]">
            <el-radio 
              v-for="(option, optIndex) in currentQuestion.options" 
              :key="optIndex"
              :label="option.value"
              class="option-item"
            >
              {{ option.label }}
            </el-radio>
          </el-radio-group>
        </div>
        
        <!-- 多选题 -->
        <div v-else-if="currentQuestion.type === 'multiple'" class="question-options">
          <el-checkbox-group v-model="userAnswers[currentQuestionIndex]">
            <el-checkbox 
              v-for="(option, optIndex) in currentQuestion.options" 
              :key="optIndex"
              :label="option.value"
              class="option-item"
            >
              {{ option.label }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        
        <!-- 判断题 -->
        <div v-else-if="currentQuestion.type === 'boolean'" class="question-options">
          <el-radio-group v-model="userAnswers[currentQuestionIndex]">
            <el-radio :label="true" class="option-item">正确</el-radio>
            <el-radio :label="false" class="option-item">错误</el-radio>
          </el-radio-group>
        </div>
        
        <!-- 填空题 -->
        <div v-else-if="currentQuestion.type === 'fill'" class="question-fill">
          <el-input
            v-model="userAnswers[currentQuestionIndex]"
            type="text"
            placeholder="请输入答案"
          ></el-input>
        </div>
        
        <!-- 简答题 -->
        <div v-else-if="currentQuestion.type === 'essay'" class="question-essay">
          <el-input
            v-model="userAnswers[currentQuestionIndex]"
            type="textarea"
            :rows="6"
            placeholder="请输入答案"
          ></el-input>
        </div>
        
        <div class="question-actions">
          <el-button 
            type="warning" 
            plain
            @click="toggleMark(currentQuestionIndex)"
          >
            <i :class="isMarked(currentQuestionIndex) ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
            {{ isMarked(currentQuestionIndex) ? '取消标记' : '标记题目' }}
          </el-button>
          
          <div class="navigation-buttons">
            <el-button 
              type="primary" 
              plain
              icon="el-icon-arrow-left"
              @click="prevQuestion"
              :disabled="currentQuestionIndex === 0"
            >
              上一题
            </el-button>
            <el-button 
              type="primary"
              @click="nextQuestion"
              :disabled="currentQuestionIndex === questions.length - 1"
            >
              下一题
              <i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <div class="exam-footer">
      <el-button @click="showExitDialog">退出考试</el-button>
      <el-button type="primary" @click="showSubmitDialog">提交试卷</el-button>
    </div>
    
    <!-- 提交确认对话框 -->
    <el-dialog
      title="确认提交"
      :visible.sync="submitDialogVisible"
      width="30%"
    >
      <div class="submit-dialog-content">
        <p>您还有 <span class="warning-text">{{ questions.length - answeredCount }}</span> 题未作答，确认提交吗？</p>
        <p>提交后将无法再次修改答案。</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="submitDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitExam">确认提交</el-button>
      </span>
    </el-dialog>
    
    <!-- 退出确认对话框 -->
    <el-dialog
      title="确认退出"
      :visible.sync="exitDialogVisible"
      width="30%"
    >
      <div class="exit-dialog-content">
        <p>确认退出考试吗？</p>
        <p>您的答案将会自动保存，但计时不会暂停。</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="exitDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="exitExam">确认退出</el-button>
      </span>
    </el-dialog>
    
    <!-- 时间到对话框 -->
    <el-dialog
      title="考试时间结束"
      :visible.sync="timeUpDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="time-up-dialog-content">
        <p>考试时间已结束，系统将自动提交您的答案。</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitExam">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import CountDown from '@/components/CountDown'

export default {
  name: 'ExamTake',
  components: {
    CountDown
  },
  data() {
    return {
      exam: {
        id: '',
        title: '',
        courseName: '',
        type: '',
        startTime: 0,
        endTime: 0,
        duration: 0,
        totalScore: 0
      },
      questions: [],
      userAnswers: [],
      markedQuestions: [],
      currentQuestionIndex: 0,
      remainingTime: 0,
      submitDialogVisible: false,
      exitDialogVisible: false,
      timeUpDialogVisible: false,
      autoSaveTimer: null
    }
  },
  computed: {
    currentQuestion() {
      return this.questions[this.currentQuestionIndex] || {}
    },
    answeredCount() {
      return this.userAnswers.filter(answer => {
        if (Array.isArray(answer)) {
          return answer.length > 0
        }
        return answer !== null && answer !== undefined && answer !== ''
      }).length
    },
    progressPercentage() {
      return this.questions.length > 0 
        ? Math.round((this.answeredCount / this.questions.length) * 100) 
        : 0
    },
    progressColor() {
      if (this.progressPercentage < 30) {
        return '#F56C6C'
      } else if (this.progressPercentage < 70) {
        return '#E6A23C'
      } else {
        return '#67C23A'
      }
    }
  },
  created() {
    this.fetchExamData()
    window.addEventListener('beforeunload', this.handleBeforeUnload)
  },
  mounted() {
    // 自动保存答案，每分钟一次
    this.autoSaveTimer = setInterval(this.autoSaveAnswers, 60000)
  },
  beforeDestroy() {
    window.removeEventListener('beforeunload', this.handleBeforeUnload)
    if (this.autoSaveTimer) {
      clearInterval(this.autoSaveTimer)
    }
  },
  methods: {
    ...mapActions(['getExamDetail', 'getExamQuestions', 'submitExamAnswers', 'saveExamProgress']),
    async fetchExamData() {
      try {
        const examId = this.$route.params.id
        
        // 获取考试详情
        const examData = await this.getExamDetail(examId)
        this.exam = examData
        
        // 计算剩余时间
        const now = Date.now()
        this.remainingTime = Math.max(0, this.exam.endTime - now)
        
        // 获取考试题目
        const questionsData = await this.getExamQuestions(examId)
        this.questions = questionsData
        
        // 初始化答案数组
        this.initAnswers()
        
        // 尝试恢复之前的答案
        this.restoreSavedAnswers()
      } catch (error) {
        console.error('获取考试数据失败', error)
        this.$message.error('获取考试数据失败')
        this.$router.push('/exams')
      }
    },
    initAnswers() {
      this.userAnswers = this.questions.map(question => {
        switch (question.type) {
          case 'multiple':
            return []
          case 'single':
          case 'boolean':
          case 'fill':
          case 'essay':
            return ''
          default:
            return ''
        }
      })
    },
    restoreSavedAnswers() {
      // 实际项目中这里应该从本地存储或API获取之前保存的答案
      const savedAnswers = localStorage.getItem(`exam_${this.exam.id}_answers`)
      const savedMarks = localStorage.getItem(`exam_${this.exam.id}_marks`)
      
      if (savedAnswers) {
        try {
          const parsedAnswers = JSON.parse(savedAnswers)
          this.userAnswers = parsedAnswers
        } catch (e) {
          console.error('恢复答案失败', e)
        }
      }
      
      if (savedMarks) {
        try {
          this.markedQuestions = JSON.parse(savedMarks)
        } catch (e) {
          console.error('恢复标记失败', e)
        }
      }
    },
    autoSaveAnswers() {
      // 保存答案到本地存储
      localStorage.setItem(`exam_${this.exam.id}_answers`, JSON.stringify(this.userAnswers))
      localStorage.setItem(`exam_${this.exam.id}_marks`, JSON.stringify(this.markedQuestions))
      
      // 实际项目中这里应该调用API保存答案到服务器
      this.saveExamProgress({
        examId: this.exam.id,
        answers: this.userAnswers,
        markedQuestions: this.markedQuestions
      }).catch(error => {
        console.error('自动保存失败', error)
      })
    },
    handleBeforeUnload(event) {
      // 离开页面前提示用户
      event.preventDefault()
      event.returnValue = '考试尚未完成，确定要离开吗？'
    },
    getQuestionTypeText(type) {
      const typeMap = {
        single: '单选题',
        multiple: '多选题',
        boolean: '判断题',
        fill: '填空题',
        essay: '简答题'
      }
      return typeMap[type] || '未知类型'
    },
    getExamTypeText(type) {
      const typeMap = {
        quiz: '随堂测验',
        midterm: '期中考试',
        final: '期末考试'
      }
      return typeMap[type] || '未知类型'
    },
    getQuestionButtonType(index) {
      if (this.currentQuestionIndex === index) {
        return 'primary'
      }
      
      if (this.isMarked(index)) {
        return 'danger'
      }
      
      const answer = this.userAnswers[index]
      if (Array.isArray(answer) ? answer.length > 0 : answer) {
        return 'success'
      }
      
      return 'info'
    },
    isMarked(index) {
      return this.markedQuestions.includes(index)
    },
    toggleMark(index) {
      const markIndex = this.markedQuestions.indexOf(index)
      if (markIndex === -1) {
        this.markedQuestions.push(index)
      } else {
        this.markedQuestions.splice(markIndex, 1)
      }
    },
    goToQuestion(index) {
      this.currentQuestionIndex = index
    },
    prevQuestion() {
      if (this.currentQuestionIndex > 0) {
        this.currentQuestionIndex--
      }
    },
    nextQuestion() {
      if (this.currentQuestionIndex < this.questions.length - 1) {
        this.currentQuestionIndex++
      }
    },
    showSubmitDialog() {
      this.submitDialogVisible = true
    },
    showExitDialog() {
      this.exitDialogVisible = true
    },
    handleTimeUp() {
      this.timeUpDialogVisible = true
    },
    async submitExam() {
      try {
        // 自动保存一次
        this.autoSaveAnswers()
        
        // 提交答案
        await this.submitExamAnswers({
          examId: this.exam.id,
          answers: this.userAnswers
        })
        
        // 清除本地存储
        localStorage.removeItem(`exam_${this.exam.id}_answers`)
        localStorage.removeItem(`exam_${this.exam.id}_marks`)
        
        this.$message.success('考试提交成功')
        
        // 跳转到结果页面
        this.$router.push(`/exam/${this.exam.id}/result`)
      } catch (error) {
        console.error('提交考试失败', error)
        this.$message.error('提交考试失败，请重试')
      }
    },
    exitExam() {
      // 自动保存一次
      this.autoSaveAnswers()
      this.$router.push('/exams')
    }
  }
}
</script>

<style lang="scss" scoped>
.exam-take-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 60px); // 减去顶部导航高度
  background-color: #f5f7fa;
}

.exam-header {
  background-color: #fff;
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .exam-title {
    font-size: 20px;
    color: #303133;
    margin: 0 0 8px;
  }
  
  .exam-meta {
    color: #606266;
    font-size: 14px;
    
    .course-name {
      margin-right: 15px;
    }
    
    .exam-type {
      background-color: #f0f9eb;
      color: #67c23a;
      padding: 2px 8px;
      border-radius: 3px;
    }
  }
  
  .exam-timer {
    text-align: center;
    
    .timer-label {
      font-size: 14px;
      color: #909399;
      margin-bottom: 5px;
    }
    
    .timer {
      font-size: 20px;
      color: #f56c6c;
      font-weight: bold;
    }
  }
}

.exam-body {
  flex: 1;
  display: flex;
  overflow: hidden;
  
  .question-nav {
    width: 250px;
    background-color: #fff;
    border-right: 1px solid #e4e7ed;
    padding: 15px;
    display: flex;
    flex-direction: column;
    
    .nav-header {
      margin-bottom: 15px;
      
      .question-count {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        color: #606266;
        
        .count {
          font-weight: bold;
          color: #409EFF;
        }
      }
    }
    
    .question-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: 20px;
      
      .question-button {
        width: 40px;
        height: 40px;
        padding: 0;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
    
    .question-legend {
      margin-top: auto;
      
      .legend-item {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        
        .legend-color {
          width: 16px;
          height: 16px;
          border-radius: 3px;
          margin-right: 8px;
        }
        
        .legend-text {
          font-size: 12px;
          color: #606266;
        }
      }
    }
  }
  
  .question-content {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    background-color: #fff;
    margin: 15px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .question-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 15px;
      
      .question-type-tag {
        background-color: #ecf5ff;
        color: #409EFF;
        padding: 5px 10px;
        border-radius: 3px;
        font-size: 14px;
      }
      
      .question-score {
        color: #f56c6c;
        font-weight: bold;
      }
    }
    
    .question-title {
      font-size: 16px;
      color: #303133;
      margin-bottom: 20px;
      line-height: 1.6;
      
      .question-index {
        font-weight: bold;
      }
    }
    
    .question-options {
      margin-bottom: 30px;
      
      .option-item {
        display: block;
        margin-bottom: 15px;
      }
    }
    
    .question-fill, .question-essay {
      margin-bottom: 30px;
    }
    
    .question-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 30px;
      
      .navigation-buttons {
        display: flex;
        gap: 10px;
      }
    }
  }
}

.exam-footer {
  background-color: #fff;
  padding: 15px 20px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.submit-dialog-content, .exit-dialog-content, .time-up-dialog-content {
  text-align: center;
  
  .warning-text {
    color: #f56c6c;
    font-weight: bold;
  }
}
</style> 